package com.weilx959.spt.core.component;

import com.weilx959.spt.core.utils.StringUtil;
import com.weilx959.spt.core.vo.PluginItemVO;
import javafx.collections.ObservableList;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.Tooltip;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Iterator;
import java.util.Optional;

/**
 * 插件列表单元格，定义单元格显示样式及包含属性
 *
 * @author weilx
 * @since 2024-04-16
 */
@Slf4j
public class PluginListCell extends ListCell<PluginItemVO> {
    private final StackPane stackPane;

    private final Label label;

    private final Tooltip tooltip;

    public PluginListCell() {
        label = new Label();
        tooltip = new Tooltip();
        stackPane = new StackPane();
        stackPane.getChildren().add(label);
        stackPane.getStyleClass().add("plugin-item");
    }

    @Override
    protected void updateItem(PluginItemVO item, boolean empty) {
        super.updateItem(item, empty);

        if (empty || item == null) {
            super.setText(null);
            super.setGraphic(null);
            super.setTooltip(null);
            return;
        }
        String pluginName = item.getPlugin().getName();

        if (StringUtils.isNotBlank(item.getPlugin().getIconPath())) {
            label.setGraphic(new ImageView(new Image(item.getPlugin().getIconPath(),
                34, 34, true, true)));
            label.setText(null);
        } else {
            label.setGraphic(null);
            label.setText(pluginName.substring(0, 1));
        }
        this.addStyle(item.getPlugin().getIconStyle());
        super.setText(null);
        super.setGraphic(stackPane);

        // 设置tips
        if (StringUtils.isNotBlank(item.getPlugin().getDescription())) {
            tooltip.setText(item.getPlugin().getDescription());
            super.setTooltip(tooltip);
        } else {
            super.setTooltip(null);
        }
    }

    private void addStyle(String styleName) {
        if (StringUtils.isBlank(styleName)) {
            return;
        }
        ObservableList<String> labelStyleClass = label.getStyleClass();
        Iterator<String> iterator = labelStyleClass.iterator();

        while (iterator.hasNext()) {
            if ("label".equals(iterator.next())) {
                continue;
            }
            iterator.remove();
        }
        Optional.of(styleName)
            .map(StringUtil::convertToCssClass)
            .ifPresent(labelStyleClass::add);
    }
}
